package com.cqfae.deploycentral.app.config;

import com.cqfae.deploycentral.api.utils.IdGenerator;
import com.cqfae.deploycentral.app.base.BaseConstantCode;
import com.cqfae.deploycentral.app.base.BaseConstants;
import com.cqfae.deploycentral.app.dao.entity.ScheduledExecHistory;
import com.cqfae.deploycentral.app.dao.mapper.ScheduledExecHistoryMapper;
import com.cqfae.deploycentral.app.services.ExpectPublishEnqueueService;
import com.cqfae.deploycentral.app.services.InspectService;
import com.cqfae.deploycentral.app.services.WindowInfoService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;

import static com.cqfae.deploycentral.app.base.BaseConstantCode.SCHEDULED_EXEC_NOTHING;

/**
 * Created by YANGHENG940 on 2017/7/19.
 */
@Component
@Configurable
@EnableScheduling
public class ScheduledConfig {

    private static Logger logger = LoggerFactory.getLogger(ScheduledConfig.class);

    @Autowired
    private WindowInfoService windowInfoService;

    @Autowired
    private ExpectPublishEnqueueService expectPublishEnqueueService;

    @Autowired
    private ScheduledExecHistoryMapper scheduledExecHistoryMapper;

    @Autowired
    private InspectService inspectService;

    public static final String NOTEXTINFO = "execUpdateExpectPublishEqueue,execAutoInsertWindowPlans";

    @Autowired
    private IdGenerator idGenerator;

    //执行创建发布窗口任务
    @Scheduled(cron = "${scheduled.cron.createDeployWindow}")
    public void execCreateDeployWindow() {
        Date date = new Date();
        execCommonContent(date, "execCreateDeployWindow",
                getStatus(windowInfoService.createWindowForNextMonth(date)));
    }

    //执行关闭发布窗口任务
    @Scheduled(cron = "${scheduled.cron.closeWindow}")
    public void execCloseWindow() {
        Date date = new Date();
        execCommonContent(date, "execCloseWindow",
                getStatus(windowInfoService.closeWindowForDay(date)));
    }

    @Scheduled(cron = "${scheduled.cron.buildPackageToday}")
    public void execWindowPlansPackage() {
        Date date = new Date();
        execCommonContent(date, "execWindowPlansPackage",
                getStatus(windowInfoService.packageAppForDay(date)));
    }

    //执行自动更改待发布计划表的任务
    @Scheduled(cron = "${scheduled.cron.updateExpectPublishEqueue}")
    public void execUpdateExpectPublishEqueue() {
        Date date = new Date();
        execCommonContent(date, "execUpdateExpectPublishEqueue",
                getStatus(expectPublishEnqueueService.updateExpectPublish()));
    }

    //执行自动新增窗口计划的任务
    @Scheduled(cron = "${scheduled.cron.autoInsertWindowPlans}")
    public void execAutoInsertWindowPlans() {
        Date date = new Date();
        execCommonContent(date, "execAutoInsertWindowPlans",
                getStatus(expectPublishEnqueueService.autoInsertWindowPlans()));
    }

    // 定时从Jenkins获取巡检数据
    @Scheduled(cron = "${scheduled.cron.execJenkinsInspect}")
    public void execJenkinsInspect() {
        Date date = new Date();
        execCommonContent(date, "execJenkinsInspect",
                getStatus(inspectService.execJenkinsInspect()));
    }

    /**
     * @param count
     * @return
     */
    private Integer getStatus(int count) {
        if (count > 0) {
            return BaseConstantCode.SCHEDULED_EXEC_SUCCESS;
        } else {
            return SCHEDULED_EXEC_NOTHING;
        }
    }

    /**
     * @param date
     * @param name
     * @param status
     */
    private void execCommonContent(Date date, String name, Integer status) {
        logger.info(" ==== Scheduling execCloseWindow Start ==== {}", dateFormat().format(date));
        ScheduledExecHistory scheduledExecHistory = new ScheduledExecHistory();
        scheduledExecHistory.setId(idGenerator.nextId());
        scheduledExecHistory.setScheduledName(name);
        scheduledExecHistory.setScheduledTime(date);
        scheduledExecHistory.setCreateBy(BaseConstants.SCHEDULED_USER);
        scheduledExecHistory.setCreateTime(date);
        scheduledExecHistory.setScheduledStatus(status);
        scheduledExecHistory.setRemark(System.getProperty("spring.profiles.active"));
        if (NOTEXTINFO.contains(name) && status == SCHEDULED_EXEC_NOTHING) {
            logger.info(" ==== Info is Not Change ==== {}", name);
        } else {
            int j = scheduledExecHistoryMapper.insert(scheduledExecHistory);
            logger.info(" ==== Scheduling execCloseWindow End ==== {}", j);
        }
    }

    private SimpleDateFormat dateFormat() {
        return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    }
}
